import React from 'react';
import { connect } from 'dva';
import { Table, Row, Col, Form, Input, Radio, Button, Popconfirm, DatePicker } from 'antd';
const { RangePicker } = DatePicker;
const R = require('ramda');
import BizParams from '../../../components/commons/BizParams'
import OrderDetail from '../../../components/order/components/OrderDetail';
import RightBox from '../../../components/commons/RightBox';
import RightConstants from '../../../utils/RightConstants';
import Constants from '../../../utils/Constants';
import { download } from '../../../utils/commons'

const FormItem = Form.Item;
const RadioGroup = Radio.Group;
export default connect(({ orderManage, declaration }) => ({ orderManage, declaration }))(
    Form.create()(class OrderManage extends React.Component {
        constructor(props) {
            super(props);
        }

        componentDidMount() {
            this.props.dispatch({ type: 'orderManage/queryOrderManageList', payload: {} });//查询订单列表
        }

        collectSearchCondition = () => {
            let conditions = this.props.form.getFieldsValue();
            conditions.beginTime = conditions.submitTime ? conditions.submitTime[0].format(Constants.DATEFORMAT) : undefined,
                conditions.endTime = conditions.submitTime ? conditions.submitTime[1].format(Constants.DATEFORMAT) : undefined,
                conditions.submitTime = undefined;
            conditions.page = this.props.orderManage.page;
            return conditions;
        }

        onView = (record) => {
            this.handleOpenOrderDetail(record, true, true, true, true, {}, "1");
        }

        onEdit = (record) => {
            this.handleOpenOrderDetail(record, false, true, true, false, this.collectSearchCondition(), "1");
        }

        onUploadConfirmLetter = (record) => {
            this.handleOpenOrderDetail(record, true, false, true, true, this.collectSearchCondition(), "5");
        }

        onEditCost = (record) => {
            this.handleOpenOrderDetail(record, true, true, false, true, this.collectSearchCondition(), "6");
        }

        onManageAttachment = (record) => {
            this.handleOpenOrderDetail(record, true, true, true, false, this.collectSearchCondition(), "4");
        }

        onReDownload = (record) => {
            let url = apiPath.mc + "/api/order/" + record.id + "/declaringorder";
            download(url, { status: record.status });
        }

        onGenerateImportCD = (record) => {
            this.handleOpenOrderDetail(record, true, true, true, true, this.collectSearchCondition(), "8");
        }

        handleOpenOrderDetail = (record, orderDisabled, letterDisabled, costDisabled, attachmentDisabled, searchConditions, tabActiveKey) => {
            this.props.dispatch({ type: 'orderManage/getOrderById', payload: { id: record.id } });//获取订单详情
            this.props.dispatch({ type: 'orderManage/queryDrawerList', payload: { cstId: record.cstid } });//查询开票人列表
            this.props.dispatch({ type: 'orderCost/queryOrderCost', payload: { id: record.id, status: "1" } });//查询费用列表
            this.props.dispatch({ type: 'orderManage/queryLinkmanList', payload: { cstId: record.cstid } });//查询联系人列表
            this.props.dispatch({ type: 'orderManage/queryAddressList', payload: { cstId: record.cstid } });//查询货物存放地址列表
            this.props.dispatch({ type: 'orderManage/queryBuyerList', payload: { cstId: record.cstid } });//查询境外买家
            this.props.dispatch({ type: 'orderManage/querySupplyGoods', payload: { cstId: record.cstid } });//查询境内货源地
            this.props.dispatch({ type: 'orderManage/queryTgManagers' });//查询通关专员
            this.props.dispatch({ type: 'declaration/queryAllLesseeDeclaration' });  //查询市场采购资源-报关抬头
            this.refs.orderDetail.handleOpen(orderDisabled, letterDisabled, costDisabled, attachmentDisabled, searchConditions, tabActiveKey);
        }

        handleSearch = (flag) => {
            let values = this.props.form.getFieldsValue();
            let newPage = this.props.orderManage.page;
            if (flag) newPage.page = 1;
            this.props.dispatch({
                type: 'orderManage/queryOrderManageList',
                payload: {
                    cstName: values.cstName,
                    orderNo: values.orderNo,
                    contractNo: values.contractNo,
                    declarationType: values.declarationType,
                    status: values.status,
                    beginTime: values.submitTime && values.submitTime.length > 0 ? values.submitTime[0].format(Constants.DATEFORMAT) : undefined,
                    endTime: values.submitTime && values.submitTime.length > 1 ? values.submitTime[1].format(Constants.DATEFORMAT) : undefined,
                    page: newPage
                }
            });
        };

        handleCopy = (record) => {
            this.props.dispatch({
                type: 'orderManage/copyOrderById',
                payload: {
                    id: record.id,
                    searchConditions: this.collectSearchCondition()
                }
            });
        }

        handleDelete = (record) => {
            this.props.dispatch({
                type: 'orderManage/deleteOrderById',
                payload: {
                    id: record.id,
                    searchConditions: this.collectSearchCondition()
                }
            });
        }

        handleCancelChargeConfirm = (record) => {
            this.props.dispatch({
                type: 'orderManage/cancelChargeConfirm',
                payload: {
                    orderId: record.id,
                    onSuccess: () => { this.handleSearch() }
                }
            });
        }

        handleReturnOrder = (record) => {
            this.props.dispatch({
                type: 'orderManage/returnOrder',
                payload: {
                    id: record.id,
                    searchConditions: this.collectSearchCondition(),
                    gobackreason: Constants.RETURN_ORDER
                }
            });
        }

        columns = [
            { title: '订单编号', dataIndex: 'orderno', key: 'orderno' },
            { title: '客户名称', dataIndex: 'companyname', key: 'companyname' },
            { title: '合同协议号', dataIndex: 'contractno', key: 'contractno' },
            { title: '报关方式', dataIndex: 'declarationTypeName', key: 'declarationTypeName' },
            { title: '报关口岸', dataIndex: 'portofentryidName', key: 'portofentryidName' },
            { title: '总货值', dataIndex: 'totleamount', key: 'totleamount' },
            { title: '币种', dataIndex: 'currencytype', key: 'currencytype' },
            { title: '提交人', dataIndex: 'creatorName', key: 'creatorName' },
            { title: '创建时间', dataIndex: 'createtime', key: 'createtime' },
            { title: '预计报关时间', dataIndex: 'exporttime', key: 'exporttime' },
            {
                title: '状态', dataIndex: 'status', key: 'status',
                render: (text, record, index) => {
                    let tgyStatus = "";
                    if(record.billId && record.tgyDeclaring === '1'){
                        tgyStatus = `(通关易：${ record.tgyStatus && Constants.TGY_STATUS[record.tgyStatus] ? Constants.TGY_STATUS[record.tgyStatus] : "尚未同步，请等待"})`
                    }
                    return (Constants.ORDERSTATUS[record.status] + tgyStatus);
                }
            },
            {
                title: '操作', key: 'key_oprator',
                render: (text, record, index) => {
                    let split = <span className="ant-divider" />
                    let copyLink = <Popconfirm placement="leftTop" onConfirm={this.handleCopy.bind(this, record)} okText="是" cancelText="否"
                        title={'复制原订单的一份草稿, 保留原订单附件之外的所有基本信息, 订单号生成方式会默认为系统生成, 是否继续复制?'}>
                        <a href="#">复制</a>
                    </Popconfirm>
                    copyLink = <RightBox resource={RightConstants.ORDER.ORDER_MANAGE_COPY} split={true}>{copyLink}</RightBox>
                    let costLink = <RightBox resource={RightConstants.ORDER.ORDER_MANAGE_COST} split={true}><a href="#" onClick={this.onEditCost.bind(this, record)}>费用</a></RightBox>
                    let viewLink = <a href="#" onClick={this.onView.bind(this, record)}>查看</a>
                    let editLink = <RightBox resource={RightConstants.ORDER.ORDER_MANAGE_EDIT} split={true}><a href="#" onClick={this.onEdit.bind(this, record)}>编辑</a></RightBox>
                    let deleteLink = <Popconfirm onConfirm={this.handleDelete.bind(this, record)} okText="是" cancelText="否"
                        placement="leftTop" title={'数据删除后将不可以恢复，是否继续删除？'}>
                        <a href="#">删除</a>
                    </Popconfirm>
                    deleteLink = <RightBox resource={RightConstants.ORDER.ORDER_MANAGE_DELETE} split={true}>{deleteLink}</RightBox>
                    let confirmLetterLink = <RightBox resource={RightConstants.ORDER.ORDER_MANAGE_LETTER} split={true}><a href="#" onClick={this.onUploadConfirmLetter.bind(this, record)}>确认函</a></RightBox>
                    let attachmentLink = <RightBox resource={RightConstants.ORDER.ORDER_MANAGE_ATTACH} split={true}><a href="#" onClick={this.onManageAttachment.bind(this, record)}>附件</a></RightBox>

                    let returnLink = <Popconfirm onConfirm={this.handleReturnOrder.bind(this, record)} okText="是" cancelText="否"
                        placement="leftTop" title={'订单将退回待补充资料状态，包括费用，已关联外汇，通关信息，预开票在内的信息都会被删除，是否继续？'}>
                        <a href="#">退回</a>
                    </Popconfirm>
                    returnLink = <RightBox resource={RightConstants.ORDER.ORDER_MANAGE_RETURN_ORDER} split={true}>{returnLink}</RightBox>

                    //会员客户下的单只到生成报关资料，屏蔽一些操作
                    let csttype = record.csttype === '2'; // 2：微信转移的客户，为true的话某些操作就是null
                    costLink = csttype ? null : costLink;
                    confirmLetterLink = csttype ? null : confirmLetterLink;
                    attachmentLink = csttype ? null : attachmentLink;

                    let reDownloadLink = <RightBox resource={RightConstants.ORDER.ORDER_APPROVAL_REDOWNLOAD} split={true}><a href="#" onClick={this.onReDownload.bind(this, record)}>下载报关资料</a></RightBox>
                    let gennerateCD = <RightBox resource={RightConstants.ORDER.ORDER_MANAGE_GENERATE} split={true}><a href="#" onClick={this.onGenerateImportCD.bind(this, record)}>生成报关资料</a></RightBox>

                    let cancelChargeConfirm = <Popconfirm onConfirm={this.handleCancelChargeConfirm.bind(this, record)} okText="是" cancelText="否"
                        placement="leftTop" title={'取消费用收齐，您可能需要重新走(预)开票、验票流程，订单如果已经办理完毕则会回退到报关中，是否继续操作?'}>
                        <a href="#">取消费用收齐</a>
                    </Popconfirm>
                    cancelChargeConfirm = <RightBox resource={RightConstants.ORDER.ORDER_MANAGE_COST_CANCEL} split={true}>{cancelChargeConfirm}</RightBox>
                    cancelChargeConfirm = record.chargestatus === '2' ? cancelChargeConfirm : undefined;
                    let operaters = {
                        "1": <span>{copyLink}{costLink}{editLink}{deleteLink}{viewLink}</span>,
                        "2": <span>{copyLink}{costLink}{attachmentLink}{cancelChargeConfirm}{viewLink}</span>,
                        "3": <span>{copyLink}{costLink}{editLink}{deleteLink}{cancelChargeConfirm}{viewLink}</span>,
                        "4": <span>{copyLink}{costLink}{confirmLetterLink}{attachmentLink}{cancelChargeConfirm}{viewLink}</span>,
                        "5": <span>{copyLink}{costLink}{gennerateCD}{attachmentLink}{returnLink}{cancelChargeConfirm}{viewLink}</span>,
                        "6": <span>{copyLink}{costLink}{reDownloadLink}{attachmentLink}{cancelChargeConfirm}{viewLink}</span>,
                        "7": <span>{copyLink}{reDownloadLink}{cancelChargeConfirm}{viewLink}</span>
                    }
                    return (operaters[record.status]);
                }
            }];

        render() {
            let dataSource = R.isNil(this.props.orderManage.dataSource) ? {} : this.props.orderManage.dataSource;
            let formItemLayout = { labelCol: { span: 6 }, wrapperCol: { span: 18 } };
            const { getFieldDecorator } = this.props.form;
            let values = this.props.form.getFieldsValue();
            let pagination = {
                showTotal: total => `共 ${total} 条数据`,
                current: this.props.orderManage.page.page,
                pageSize: this.props.orderManage.page.size,
                total: this.props.orderManage.page.totalRow,
                showSizeChanger: true,
                onShowSizeChange: (current, size) => {
                    let newPage = this.props.orderManage.page;
                    newPage.size = size;
                    newPage.page = 1;
                    this.props.dispatch({
                        type: 'orderManage/queryOrderManageList',
                        payload: {
                            cstName: values.cstName,
                            orderNo: values.orderNo,
                            contractNo: values.contractNo,
                            declarationType: values.declarationType,
                            status: values.status,
                            beginTime: values.submitTime && values.submitTime.length > 0 ? values.submitTime[0].format(Constants.DATEFORMAT) : undefined,
                            endTime: values.submitTime && values.submitTime.length > 1 ? values.submitTime[1].format(Constants.DATEFORMAT) : undefined,
                            page: newPage
                        }
                    });
                },
                onChange: (pageNumber, pageSize) => {
                    let newPage = this.props.orderManage.page;
                    newPage.page = pageNumber;
                    this.props.dispatch({
                        type: 'orderManage/queryOrderManageList',
                        payload: {
                            cstName: values.cstName,
                            orderNo: values.orderNo,
                            contractNo: values.contractNo,
                            declarationType: values.declarationType,
                            status: values.status,
                            beginTime: values.submitTime && values.submitTime.length > 0 ? values.submitTime[0].format(Constants.DATEFORMAT) : undefined,
                            endTime: values.submitTime && values.submitTime.length > 1 ? values.submitTime[1].format(Constants.DATEFORMAT) : undefined,
                            page: newPage
                        }
                    });
                }
            }

            //统计信息
            let statistics = this.props.orderManage.statistics;
            let title = "";
            statistics.map(item => title = title + item.currency + ": " + item.totalAmt + " | ")
            title = <span style={{ color: 'red' }}>{"金额统计 => " + (title ? title.substr(0, title.length - 3) : "")}</span>;

            return (
                <div>
                    <Row>
                        <Col span={6}><FormItem {...formItemLayout} label={'客户名称'}>{getFieldDecorator('cstName')(<Input />)}</FormItem></Col>
                        <Col span={6}><FormItem {...formItemLayout} label={'订单编号'}>{getFieldDecorator('orderNo')(<Input />)}</FormItem></Col>
                    </Row>
                    <Row>
                        <Col span={6}><FormItem {...formItemLayout} label={'合同协议号'}>{getFieldDecorator('contractNo')(<Input />)}</FormItem></Col>
                        <Col span={6}><FormItem {...formItemLayout} label={'报关方式'}>
                            {getFieldDecorator('declarationType')(
                                <BizParams sprCode={"declarationtype"} style={{ width: '100%' }} all={true} />
                            )}
                        </FormItem></Col>
                    </Row>
                    <Row>
                        <Col span={6}>
                            <FormItem {...formItemLayout} label={'下单时间'}>
                                {getFieldDecorator('submitTime')(
                                    <RangePicker
                                        style={{ width: '100%' }}
                                        showTime={{ format: 'YYYY-MM-DD' }}
                                        format="YYYY-MM-DD"
                                        placeholder={['开始时间', '结束时间']}
                                    />
                                )}
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={6}>
                            <FormItem {...formItemLayout} label={'状态'}>
                                {getFieldDecorator('status', {
                                    initialValue: ""
                                })(
                                    <RadioGroup style={{ width: 800 }}>
                                        <Radio value="">全部</Radio>
                                        <Radio value="1">草稿</Radio>
                                        <Radio value="2">待通关受理</Radio>
                                        <Radio value="3">待补充资料</Radio>
                                        <Radio value="4">待签确认函</Radio>
                                        <Radio value="5">待报关</Radio>
                                        <Radio value="6">报关中</Radio>
                                        <Radio value="7">办理完毕</Radio>
                                    </RadioGroup>
                                    )}
                            </FormItem>
                        </Col>
                        <Col span={6} style={{ float: 'right' }}>
                            <Button type="primary" icon="search" style={{ marginRight: 5 }} onClick={this.handleSearch.bind(this, true)}>查询</Button>
                        </Col>
                    </Row>
                    <Table
                        title={() => title}
                        rowKey={record => record.id}
                        dataSource={this.props.orderManage.list}
                        columns={this.columns} bordered={true}
                        size={'middle'}
                        pagination={pagination}
                        scroll={{ x: 1400 }}
                    />
                    <OrderDetail ref={"orderDetail"} cstId={dataSource.cstid} {...this.props.orderManage} dispatch={this.props.dispatch} refreshList={this.handleSearch} />
                </div>
            )
        }
    })
)
